<script setup lang="ts">
import useToast from '@/hooks/useToast';
import MsgRequest from '@/request/msgRequest';
import { useAppStore } from '@/store';
import to from '@/utils/to';
import zPaging from 'z-paging/components/z-paging/z-paging.vue';

const pagingRef = ref<InstanceType<typeof zPaging> | null>(null);
const msgList = ref<IObtainMessageList[]>([]);
const store = useAppStore();
const { showToast } = useToast();

const fetchObtainMessageList = async (pageNo: number) => {
  pagingRef.value?.complete([]);
  const [err, res] = await to(MsgRequest.ObtainMessageList({ pageNo, pageSize: 10, hasLoading: true }));
  if (err) {
    pagingRef.value?.complete(false);
    return;
  }
  pagingRef.value?.complete(res.data.list);
};

// 处理消息已读
const fetchMessageRead = (remindId: number) => {
  MsgRequest.MessageRead({ remindId }).then(() => {
    showToast('已读成功');
    msgList.value = msgList.value.map((item) => {
      if (item.remindId === remindId) {
        return { ...item, isRead: 1 };
      }
      return item;
    });
  });
};
</script>

<template>
  <NotLogged v-if="!useAppStore().$state.token" />
  <view class="pb-0" :style="{ height: `calc(100vh - ${store.$state.tabbarHeight}px)` }" v-else>
    <z-paging ref="pagingRef" v-model="msgList" @query="fetchObtainMessageList" :auto-height="false" :fixed="false">
      <view class="mx-12px c-pd c-br bg-white mt-12px" v-for="(item, index) in msgList" :key="index" @click="fetchMessageRead(item.remindId)">
        <view class="flex justify-between">
          <view class="fw-bold" v-if="item.remindType === 1">系统消息 <text class="c-text-12 ml-4px c-red" v-if="!item.isRead">未读</text></view>
          <view class="fw-bold" v-if="item.remindType === 2">订单消息 <text class="c-text-12 ml-4px c-red" v-if="!item.isRead">未读</text></view>
          <view class="fw-bold" v-if="item.remindType === 3">异常消息 <text class="c-text-12 ml-4px c-red" v-if="!item.isRead">未读</text></view>
          <text class="c-text-color-grey c-text-12">{{ item.createDate }}</text>
        </view>
        <view class="mt-12px">
          {{ item.remindContent }}
        </view>
      </view>
    </z-paging>
  </view>

  <TabBar active-tab="消息" />
</template>
